const http = require("http");
const cheerio = require("cheerio");
const fs = require("fs");
const path = require("path");
const url = require("url");

var newsList = [];
var filePath = path.join(__dirname,"/news.html");
        fs.readFile(filePath,(err,data)=>{
            if(err){
                console.log(err);
            }else{
                var str=data.toString();
                var $ = cheerio.load(str);
                $(".news-model a").each((i,el)=>{
                    if($(el).text().indexOf("2018")>-1){
                        var newsTitle = $(el).text();
                        var createTime = $(el).next().text();
                        var newsObj = {"newsTitle":newsTitle,"createTime":createTime};
                        newsList.push(newsObj);
                    }
                })
            }
        })

http.createServer((req,res)=>{
    var urlObj = url.parse(req.url);
    var pathname = urlObj.pathname;
    if(pathname=="/"){  
        var newsStr = JSON.stringify(newsList);
        res.writeHead(200,{"Content-Type":"text/plain,charset=utf8"});
        res.write(newsStr);
        res.end();
        
    }
}).listen(8081)